/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;

public class Http extends Thread {

    private HttpConnection c;
    private InputStream is;
    private OutputStream os;
    private Timer t;
    private TimeOut to;
    private HttpListener iListener;
    public String url;
    private String data, httpResponse;
    public int KTimeOut = 60000;    //koneksi time out setelah 60 detik
    private boolean isGet, isStop;
    private int mode;

    public Http(String aUrl, int Mode, HttpListener aListener) {
        url = aUrl;
        mode = Mode;
        data = "";
        iListener = aListener;
        httpResponse = "";
        c = null;
        is = null;
        os = null;
        t = new Timer();
        to = new TimeOut(this);
        isGet = true;
        isStop = false;
    }

    public Http(String aUrl, String aPostData, int Mode, HttpListener aListener) {
        url = aUrl;
        data = aPostData;
        mode = Mode;
        iListener = aListener;
        httpResponse = "";
        c = null;
        is = null;
        os = null;
        t = new Timer();
        to = new TimeOut(this);
        isGet = false;
        isStop = false;
    }

    /**
     * menghapus RMS
     * @param name  nama RMS yang akan dihapus
     */
    public static void deleteRMS(String name) {
        try {
            RecordStore.deleteRecordStore(name);
        } catch (Exception e) {
        }
    }

    /**
     * membaca data dari RMS
     * @param name  nama RMS yang akan dibaca
     * @return
     */
    public static String readFromRMS(String name) {
        String hasil = "";
        RecordStore rs = null;
        try {
            rs = RecordStore.openRecordStore(name, true);
            RecordEnumeration re = rs.enumerateRecords(null, null, false);
            while (re.hasNextElement()) {
                hasil = hasil + new String(re.nextRecord(), "ISO-8859-1");
            }
        } catch (Exception e) {
            System.gc();
        } finally {
            try {
                rs.closeRecordStore();
            } catch (Exception e) {
            }
        }
        return hasil;
    }

    /**
     * menyimpan data ke dalam rms
     */
    public static void saveToRMS(String name, byte[] data, boolean delete) {
        if (delete) {
            try {
                RecordStore.deleteRecordStore(name);
            } catch (Exception e) {
            }
        }
        RecordStore rs = null;
        try {
            rs = RecordStore.openRecordStore(name, true);
            rs.addRecord(data, 0, data.length);
            data = null;
            name = null;
            System.gc();
        } catch (Exception e) {
            e.printStackTrace();
            System.gc();
        } finally {
            try {
                rs.closeRecordStore();
            } catch (Exception e) {
            }
        }
    }

    public void stop() {
        isStop = true;
        if (is != null) {
            try {
                is.close();
            } catch (Exception e) {
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (Exception e) {
            }
        }
        if (c != null) {
            try {
                c.close();
            } catch (Exception e) {
            }
        }
    }

    class TimeOut extends TimerTask {

        private Http http;

        public TimeOut(Http h) {
            http = h;
        }

        public void run() {
            stop();
            iListener.onHttpFailed("Connection time out", http, mode);
        }
    }

    public void run() {
        int rc;
        try {
            t.schedule(to, KTimeOut);
            c = (HttpConnection) Connector.open(url);
            c.setRequestProperty("User-Agent", "" + System.getProperty("microedition.platform"));
            c.setRequestProperty("accept", "text/html,text/css,multipart/mixed,application/java-archive, application/java, application/x-java-archive, text/vnd.sun.j2me.app-descriptor, application/vnd.oma.drm.message, application/vnd.oma.drm.content, application/vnd.oma.dd+xml, application/vnd.oma.drm.rights+xml, application/vnd.oma.drm.rights+wbxml, application/x-nokia-widget, */*");
            if (isGet) {
                c.setRequestMethod(HttpConnection.GET);
            } else {
                c.setRequestMethod(HttpConnection.POST);
                c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                c.setRequestProperty("Content-Length", "" + data.length());
                //Post data
                if (data != null && data.length() > 0) {
                    os = c.openOutputStream();
                    byte[] buf = data.getBytes("ISO-8859-1");
                    int start = 0;
                    int len = 1024;
                    while (buf.length > start) {
                        if (start + len > buf.length) {
                            len = buf.length - start;
                        }
                        os.write(buf, start, len);
                        start = start + len;
                    }
                    try {
                        os.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                        t.cancel();
                        if (!isStop) {
                            iListener.onHttpFailed(e.getMessage(), this, mode);
                            return;
                        } else {
                            return;
                        }
                    }
                    os = null;
                }
            }
            rc = c.getResponseCode();
            if (rc == HttpConnection.HTTP_OK) {
                int length = (int) c.getLength();
                is = c.openInputStream();
                //////////////////// inputStream to string ////////////////////
                int ch = 0;
                byte[] buf = new byte[1024];
                StringBuffer sb = new StringBuffer();
                do {
                    try {
                        ch = is.read(buf);
                    } catch (Exception e) {
                        if (sb.length() == 0 || sb.length() < length) {
                            t.cancel();
                            to = null;
                            t = null;
                            System.gc();
                            throw e;
                        } else {
                            ch = -1;
                        }
                    }
                    if (ch != -1) {
                        t.cancel();
                        to = null;
                        t = null;
                        System.gc();
                        sb.append(new String(buf, 0, ch, "ISO-8859-1"));
                        t = new Timer();
                        to = new TimeOut(this);
                        t.schedule(to, KTimeOut);
                    }
                } while (ch != -1);
                httpResponse = sb.toString();
                //////////////////end ////////////////////////////
                t.cancel();
                if (!isStop) {
                    iListener.onHttpSuccess(httpResponse, this, mode);
                }
            } else if (rc == HttpConnection.HTTP_BAD_REQUEST) {
                t.cancel();
                if (!isStop) {
                    iListener.onHttpFailed("Response Error : "+rc, this, mode);
                }
            } else {
                t.cancel();
                if (!isStop) {
                    iListener.onHttpFailed("Response Error : "+rc, this, mode);
                }
            }
        } catch (Exception e) {
            t.cancel();
            if (!isStop) {
                iListener.onHttpFailed(e.getMessage(), this, mode);
            }
        } finally {
            stop();
        }
    }
}

